package com.miaosmart.interceptor;

import com.miaosmart.common.context.UserContext;
import com.miaosmart.dto.UserInfoDTO;
import com.miaosmart.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行登录和注册请求
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login") || requestURI.contains("/register") || requestURI.contains("/send-verification-code")) {
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 验证token
            if (jwtUtil.validateToken(token)) {
                // 解析token并获取用户信息
                Claims claims = jwtUtil.getClaimsFromToken(token);
                
                // 从claims中提取用户信息并存储到UserContext中
                String userId = claims.get("userId", String.class);
                String username = claims.get("username", String.class);
                String role = claims.get("role", String.class);
                UserInfoDTO user = new UserInfoDTO(userId, username, role);
                UserContext.setUser(user);
                
                return true;
            }
        }

        // token无效，返回401未授权状态码
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Unauthorized: Invalid or missing token");
        return false;
    }
} 